package com.example.pyphone3;

import android.Manifest;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import org.apache.commons.lang3.StringUtils;

import android.content.pm.PackageManager;
import android.os.Bundle;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.net.URI;
import java.io.File;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;

import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.net.Uri;
import android.view.Menu;
import android.view.MenuItem;

import android.os.Looper;
import android.widget.Button;
import android.widget.EditText;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.java_websocket.handshake.ServerHandshake;

import android.telephony.SmsManager;

import SQLite.SQLFunction;
import config.GetHttpRequester;

public class MainActivity extends AppCompatActivity {
    private JWebSocketClientService.JWebSocketClientBinder binder;
    private JWebSocketClientService jWebSClientService;
    private static final int MY_PERMISSIONS_REQUEST_SEND_SMS = 1;
    private static final String TAG = MainActivity.class.getSimpleName();
    private static int duplicateSubmission = 0;
    int mYear, mMonth, mDay;
    TextView dateDisplay;
    final int DATE_DIALOG = 1;
    private static final int SEND_SMS = 100;
    private static String EnvironmentPath = Environment.getExternalStorageDirectory().getPath();
    Button btn_sql;
    static String postResultid = "0";
    SimpleDateFormat filelasttime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static String username = null;
    private static String password = null;
    private static String phoneNum = null;
    SQLFunction function = new SQLFunction();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SQLFunction.initTable(MainActivity.this);  /**【初始化数据库】**/
        btn_sql = this.findViewById(R.id.btn_sql);
        Toolbar toolbar = findViewById(R.id.toolbar);
        PermissionUtils.isGrantExternalRW(this, 1);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        getid();
    }

    @Override
    public void onResume() {
        super.onResume();
        postResultid = getid();
        if (!postResultid.equals("00") && !postResultid.equals("0") && !postResultid.equals("")) {
            new Thread(downloadRun).start();
            setContentView(R.layout.fragment_call);
            new Thread(wsRun).start();
        }
    }

    public String getid() {
        ArrayList<HashMap<String, String>> list = new ArrayList<>();
        list = function.query(MainActivity.this, postResultid, null, null);
        SDCardListener listener = new SDCardListener(getSoundRecordingPath());
        listener.startWatching();//开始监听
        if (list.size() != 0) {
            setContentView(R.layout.fragment_call);
            username = list.get(0).get("name");
            return list.get(0).get("userid");
        } else {
            return "";
        }
    }

    public static String getName() {
        return username;
    }

    public void click4(View view) {
        setContentView(R.layout.fragment_first);
    }

    public void click8(View view) {
        new Thread(getPhoneNumber).start();
        Toast.makeText(getApplicationContext(), "本机号码：" + phoneNum, Toast.LENGTH_SHORT).show();
    }

    public String getPhoneNum() {
        try {
            TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return "";
            }
            String phoneId = tm.getLine1Number();
            return phoneId;
        } catch (Exception e) {
            return "";
        }
    }

    public void clicksjk(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.btn_sql:
                DB_i_u_d_s();
                break;
        }
    }

    public void clickLogin(View view) throws Exception {
        int i = 0;
        EditText usenameText = (EditText) findViewById(R.id.et_usename);
        EditText passwordText = (EditText) findViewById(R.id.et_password);
        username = usenameText.getText().toString();
        password = passwordText.getText().toString();
        new Thread(getHttpRun).start();
        Thread.sleep(2000);
        if (!postResultid.equals("00") && !postResultid.equals("0")) {
            setContentView(R.layout.fragment_call);
            SDCardListener listener = new SDCardListener(getSoundRecordingPath());
            listener.startWatching();//开始监听
            new Thread(wsRun).start();
        } else {
            Toast.makeText(getApplicationContext(), "用户名或密码不正确！", Toast.LENGTH_SHORT).show();
        }
    }

    Runnable getPhoneNumber = new Runnable() {
        @Override
        public void run() {
            Map<String, String> params = new HashMap<>();
            params.put("phoneNum", getPhoneNum());
            try {
                phoneNum = GetHttpRequester.getHttp("http://phone.yiyatest.cn/call/getPhoneNum", params);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    Runnable getHttpRun = new Runnable() {
        @Override
        public void run() {
            Map<String, String> params = new HashMap<>();
            params.put("username", username);
            params.put("password", password);
            try {
                postResultid = GetHttpRequester.getHttp("http://phone.yiyatest.cn/call/login", params);
                postResultid = postResultid + "";
                Object[] data = {postResultid, username, password};
                if (!postResultid.equals("0")) {
                    String where1 = postResultid;
                    String where2 = username;
                    String where3 = password;
                    ArrayList<HashMap<String, String>> list = new ArrayList<>();
                    list = function.query(MainActivity.this, where1, where2, where3);
                    if(list.size()>0){
                        if (list.get(0).get("userid") == postResultid) {
                            Log.i("TAG:", "从数据库中拿到的数据 _ID为：" + list.get(0).get("_id"));
                            Log.i("TAG:", "从数据库中拿到的数据 userid：" + list.get(0).get("userid"));
                            Log.i("TAG:", "从数据库中拿到的数据name为：" + list.get(0).get("name"));
                            Log.i("TAG:", "从数据库中拿到的数据info为：" + list.get(0).get("info"));
                            Log.i("TAG:", "从数据库中拿到的数据lastcalltime：" + list.get(0).get("lastcalltime"));
                        } else {
                            function.insert(MainActivity.this, data);
                            function.insert(MainActivity.this, data);
                        }
                    } else {
                        function.insert(MainActivity.this, data);
                        function.insert(MainActivity.this, data);
                    }
                } else {
                    postResultid = "00";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public static String getSoundRecordingPath() {
        File soundRecordingfile = new File(EnvironmentPath + "/Sounds/CallRecord");
        if (soundRecordingfile.exists()) {
            return EnvironmentPath + "/Sounds/CallRecord";
        } else {
            soundRecordingfile = new File(EnvironmentPath + "/MIUI/sound_recorder/call_rec");
            if (soundRecordingfile.exists()) {
                return EnvironmentPath + "/MIUI/sound_recorder/call_rec";
            } else {
                soundRecordingfile = new File(EnvironmentPath + "/Record/Call");
                if (soundRecordingfile.exists()) {
                    return EnvironmentPath + "/Record/Call";
                } else {
                    return EnvironmentPath + "/Pictures";
                }
            }
        }
    }

    /**
     * 【操作数据库的方法】
     **/
    private void DB_i_u_d_s() {
        Log.i("TAG:", "查询数据！");
        String where1 = null;
        String where2 = null;
        String where3 = null;
        ArrayList<HashMap<String, String>> list = new ArrayList<>();
        list = function.query(MainActivity.this, where1, where2, where3);
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                Log.i("TAG:", "从数据库中拿到的数据_ID为：" + list.get(i).get("_id"));
                Log.i("TAG:", "从数据库中拿到的数据userid：" + list.get(i).get("userid"));
                Log.i("TAG:", "从数据库中拿到的数据name为：" + list.get(i).get("name"));
                Log.i("TAG:", "从数据库中拿到的数据info为：" + list.get(i).get("info"));
                Log.i("TAG:", "从数据库中拿到的数据lastcalltime：" + list.get(i).get("lastcalltime"));
            }
        } else {
            Log.i("TAG:", "从数据库中没有拿到数据！");
        }
    }

    // v: 代表你点击的控件
    public void call(View view) {
        EditText editText = (EditText) findViewById(R.id.et_input_num);
        String phone_number = editText.getText().toString(); // 获取用户输入的手机号
        phone_number = phone_number.trim();//删除字符串首部和尾部的空格
        Toast.makeText(this, phone_number, Toast.LENGTH_LONG);
        if (phone_number != null && !phone_number.equals("")) {
            Intent t = new Intent();            //调用系统的拨号服务实现电话拨打功能 打电话 Intent : 意图.我想去做一件事
            t.setAction(Intent.ACTION_CALL); // Action:动作.我具体想做什么事 Intent.ACTION_DIAL: 激活拨号界面 Intent.ACTION_CALL: 直接拨打电话
            t.setData(Uri.parse("tel:" + phone_number));  // Data: 数据.具体的动作所需要的附加数据 封装一个拨打电话的intent，并且将电话号码包装成一个Uri对象传入
            startActivity(t);// 通知系统你去帮我干活吧
        }
    }

    //发送短信
    public void sendSMSS(View view) {
        EditText editText = (EditText) findViewById(R.id.et_input_num);
        EditText SMSSText = (EditText) findViewById(R.id.SMSS_input_content);
        String phone = editText.getText().toString(); // 获取用户输入的手机号
        String content = SMSSText.getText().toString();
        if (!StringUtils.isEmpty(content) && !StringUtils.isEmpty(phone)) {
            SmsManager manager = SmsManager.getDefault();
            ArrayList<String> strings = manager.divideMessage(content);
            for (int i = 0; i < strings.size(); i++) {
                manager.sendTextMessage(phone, null, content, null, null);
            }
            Toast.makeText(MainActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "手机号或内容不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    public void cws() {
        try {
            String url = "ws://phone.yiyatest.cn/callWebSocket/" + postResultid;
            URI uri = new URI(url);
            JWebSocketClient mWs = new JWebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    System.out.println(serverHandshake);
                }

                @Override
                public void onMessage(String s) {
                    if ("dk".equals(s)) {
                        cws();
                    } else {
                        SDCardListener listener = new SDCardListener(getSoundRecordingPath());
                        listener.startWatching();//开始监听
                        String phone_number = s;
                        phone_number = phone_number.trim();
                        EditText editText = (EditText) findViewById(R.id.et_input_num);
                        editText.setText(phone_number);
                        if (phone_number != null && !phone_number.equals("") && !phone_number.equals("dk")) {
                            Intent t = new Intent();
                            t.setAction(Intent.ACTION_CALL);
                            t.setData(Uri.parse("tel:" + phone_number));
                            startActivity(t);
                        }
                    }
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    cws();
                    System.out.println(s);
                }

                @Override
                public void onError(Exception e) {
                    System.out.println(e);
                }
            };
            mWs.connect();
            System.out.println("haha");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG:
                return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
        }
        return null;
    }

    /**
     * 设置日期利用StringBuffer追加
     */
    public void display() {
        dateDisplay.setText(new StringBuffer().append(mMonth + 1).append("-").append(mDay).append("-").append(mYear).append(" "));
    }

    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            display();
        }
    };

    Runnable wsRun = new Runnable() {
        @Override
        public void run() {
            cws();
        }
    };

    /**
     * 下载线程
     */
    Runnable downloadRun = new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            String upUrl = "";
            File file1 = new File(EnvironmentPath + "/Sounds/CallRecord");
            if (file1.exists()) {
                File[] subFile = file1.listFiles();
                for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
                    if (!subFile[iFileLength].isDirectory()) {// 判断是否为文件夹
                        String filename = subFile[iFileLength].getName();
                        File file = new File(file1.toString() + "/" + filename);
                        String lasttime = filelasttime.format(file.lastModified());
                        if (file.exists()) {
                            if (file.getName().trim().toLowerCase().endsWith(".amr")) {
                                upUrl = "https://phone.yiyatest.cn/call/uploadFileToOssAmr";
                            } else {
                                upUrl = "https://phone.yiyatest.cn/call/uploadFileToOss";
                            }
                            uploadFilesHw(upUrl, file, file.getName(), lasttime);
                        }
                    }
                }
            } else {
                file1 = new File(EnvironmentPath + "/MIUI/sound_recorder/call_rec");
                if (file1.exists()) {
                    File[] subFile = file1.listFiles();
                    for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
                        if (!subFile[iFileLength].isDirectory()) {// 判断是否为文件夹
                            String filename = subFile[iFileLength].getName();
                            File file = new File(file1.toString() + "/" + filename);
                            String lasttime = filelasttime.format(file.lastModified());
                            if (file.exists()) {
                                if (file.getName().trim().toLowerCase().endsWith(".amr")) {
                                    upUrl = "https://phone.yiyatest.cn/call/uploadFileToOssAmr";
                                } else {
                                    upUrl = "https://phone.yiyatest.cn/call/uploadFileToOss";
                                }
                                uploadFilesXm(upUrl, file, file.getName(), lasttime);
                            }
                        }
                    }
                } else {
                    file1 = new File(EnvironmentPath + "/Record/Call");
                    if (file1.exists()) {
                        File[] subFile = file1.listFiles();
                        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
                            if (!subFile[iFileLength].isDirectory()) {// 判断是否为文件夹
                                String filename = subFile[iFileLength].getName();
                                File file = new File(file1.toString() + "/" + filename);
                                String lasttime = filelasttime.format(file.lastModified());
                                if (file.exists()) {
                                    if (file.getName().trim().toLowerCase().endsWith(".amr")) {
                                        upUrl = "https://phone.yiyatest.cn/call/uploadFileToOssAmr";
                                    } else {
                                        upUrl = "https://phone.yiyatest.cn/call/uploadFileToOss";
                                    }
                                    uploadFilesVivo(upUrl, file, file.getName(), lasttime);
                                }
                            }
                        }
                    }
                }
            }
            Toast.makeText(getApplicationContext(), "上传成功", Toast.LENGTH_SHORT).show();
            duplicateSubmission = 0;
            Looper.loop();//增加部分
        }
    };

    /**
     * 删除单个文件
     *
     * @param filePath 被删除文件的文件名
     * @return 文件删除成功返回true，否则返回false
     */
    public boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return false;
    }

    //上传服务器上传oss
    public void click3(View view) {
        duplicateSubmission++;
        if (duplicateSubmission == 1) {
            new Thread(downloadRun).start();
        }
    }

    public void tkkstest(String text) {
        AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
        builder1.setTitle(text);
        final String items[] = {"确定"};
        builder1.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {//-1代表没有条目被选中
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String item = items[which]; //1.把选中的条目取出来
                Toast.makeText(getApplicationContext(), item.toString(), Toast.LENGTH_LONG).show();
                dialog.dismiss();//2.然后把对话框关闭
            }
        });
        builder1.show(); //一样要show
    }

    public class PhoneReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, Intent intent) {
            TelephonyManager manager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
            switch (manager.getCallState()) {
                case TelephonyManager.CALL_STATE_IDLE:
                    tkkstest("空闲状态中");
                    Log.d(TAG, "***空闲状态中****");
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    tkkstest("振铃中");
                    Log.d(TAG, "***振铃中****");
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    tkkstest("通话中");
                    Log.d(TAG, "***通话中****");
                    break;
            }
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public String getNum(String str) {
        String str2 = "";
        str = str.trim();
        if (str != null && !"".equals(str)) {
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
                    str2 += str.charAt(i);
                }
            }
        }
        return str2;
    }

    private static String REGEX_CHINESE = "[\u4e00-\u9fa5]";// 中文正则

    public static String quzw(String str) {
        // 去除中文
//        Pattern pat = Pattern.compile(REGEX_CHINESE);
//        Matcher mat = pat.matcher(str);
//        String string = mat.replaceAll("");
        String string = str.replaceAll(REGEX_CHINESE, "");
        return string;
    }

    public static void uploadFilesHw(String requestUrl, File file, String pnum, String lasttime) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("pnum", file.getName());
        params.put("username", username);
        params.put("lasttime", lasttime);
        String fileName = file.getName().replace(" ", "");
        if (file.getName().contains("@")) {
            fileName = fileName.split("@")[1];
        }
        params.put("file", fileName);
        try {//请求普通信息
            FormFile formfile = new FormFile(fileName, file, "file", "application/octet-stream");
            boolean tf = SocketHttpRequester.post(requestUrl, params, formfile); //上传文件
            if (tf == true) {
                boolean copyFinish = copyTo(EnvironmentPath + "/Sounds/CallRecord/" + file.getName(), EnvironmentPath + "/Sounds/CallRecords/" + file.getName());
                if (copyFinish == true) {
                    File deletefile = new File(EnvironmentPath + "/Sounds/CallRecord/" + file.getName());
                    if (deletefile.isFile() && deletefile.exists()) {
                        deletefile.delete();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void uploadFilesXm(String requestUrl, File file, String pnum, String lasttime) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("pnum", file.getName());
        params.put("username", username);
        params.put("lasttime", lasttime);
        String fileName = file.getName().replace(" ", "");
        if (file.getName().contains("(")) {
            fileName = fileName.split("\\(")[1].replace(")", "");
        }
        params.put("file", fileName);
        try {//请求普通信息
            FormFile formfile = new FormFile(fileName, file, "file", "application/octet-stream");
            boolean tf = SocketHttpRequester.post(requestUrl, params, formfile); //上传文件
            if (tf == true) {
                boolean copyFinish = copyTo(EnvironmentPath + "/MIUI/sound_recorder/call_rec/" + file.getName(), EnvironmentPath + "/MIUI/sound_recorder/call_recs/" + file.getName());
                if (copyFinish == true) {
                    File deletefile = new File(EnvironmentPath + "/MIUI/sound_recorder/call_rec/" + file.getName());
                    if (deletefile.isFile() && deletefile.exists()) {
                        deletefile.delete();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void uploadFilesVivo(String requestUrl, File file, String pnum, String lasttime) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("pnum", file.getName());
        params.put("username", username);
        params.put("lasttime", lasttime);
        String fileName = file.getName().replace(" ", "");
        if (file.getName().contains("(")) {
            fileName = fileName.split(" ")[0];
        }
        params.put("file", fileName);
        try {//请求普通信息
            FormFile formfile = new FormFile(fileName, file, "file", "application/octet-stream");
            boolean tf = SocketHttpRequester.post(requestUrl, params, formfile); //上传文件
            if (tf == true) {
                boolean copyFinish = copyTo(EnvironmentPath + "/Record/Call/" + file.getName(), EnvironmentPath + "/Record/Calls/" + file.getName());
                if (copyFinish == true) {
                    File deletefile = new File(EnvironmentPath + "/Record/Call/" + file.getName());
                    if (deletefile.isFile() && deletefile.exists()) {
                        deletefile.delete();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String test2(String str) {
        Pattern p = Pattern.compile("1[345678]\\d{9}");
        Matcher m = p.matcher(str);
        while (m.find()) {
            System.out.println(m.group());
        }
        return m.group();
    }

    private static boolean copyTo(String oldpath, String newpath) throws IOException {
        File oldfile = new File(oldpath);//文件输入流，用于读取要复制的文件
        FileInputStream fileInputStream = new FileInputStream(oldfile);//要生成的新文件(指定路径如果没有则创建)
        File newfile = new File(newpath);//获取父目录
        File fileParent = newfile.getParentFile();
        System.out.println(fileParent);
        if (!fileParent.exists()) {//判断是否存在
            fileParent.mkdirs();// 创建父目录文件夹
        }
        if (!newfile.exists()) {//判断文件是否存在
            newfile.createNewFile();//创建文件
        }
        FileOutputStream fileOutputStream = new FileOutputStream(newfile);//新文件输出流
        byte[] buffer = new byte[1024];
        int len;
//将文件流信息读取文件缓存区，如果读取结果不为-1就代表文件没有读取完毕，反之已经读取完毕
        while ((len = fileInputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, len);
            fileOutputStream.flush();
        }
        fileInputStream.close();
        fileOutputStream.close();
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 对文件重命名
     *
     * @param filePath 文件的路径
     */
    public static void chageFileName(String filePath, String reName) {
        File file = new File(filePath);
        File newFile = new File(reName);
        file.renameTo(newFile);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_SEND_SMS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
            } else if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
                // Permission Denied
            } else {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
        if (requestCode == 0x11) {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.i("CMCC", "权限被允许");
            } else {
                Log.i("CMCC", "权限被拒绝");
            }
        }
        if (requestCode == 102) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.i("CMCC", "权限被允许");
            } else {
                Log.i("CMCC", "权限被拒绝");
            }
        }
        switch (requestCode) {
            case SEND_SMS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.i("CMCC", "权限被允许");
                } else {
                    // Permission Denied
                    Toast.makeText(MainActivity.this, "CALL_PHONE Denied", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}